package com.quan.weixin.api.oauth;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.quan.common.core.MyBaseController;
import com.quan.common.properties.SystemValueProperties;

import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;

/**
 * 微信公众号授权
 * 
 * @author yhaoquan
 *
 */
@Slf4j
@AllArgsConstructor
@RestController
@RequestMapping("/api/wx/mp")
public class WxMpOAuthController extends MyBaseController {

	@Autowired
	private WxMpService wxMpService;

	@Autowired
	private SystemValueProperties properties;
	
	@GetMapping(value = "oauth")
	public void authorize(Long tenantId, Long activityId, Long memberId, String openid, String pageComponent) throws Exception {
		log.debug("==>1、微信网页授权，引导用户到授权页面");
		
		// 授权回调地址
		String redirectUrl = this.properties.getWechat().getOauthCallbackUrl() ;
		
		if(null == tenantId || null == activityId) {
			throw new Exception("缺少参数，商家ID：" + tenantId + " 活动ID：" + activityId);
		}
		
		// 参数
		redirectUrl = redirectUrl + "?tenantId=" + tenantId + "&activityId=" + activityId + "&pageComponent=" + pageComponent;
		
		if(null != memberId || StringUtils.isNotBlank(openid)) {
			redirectUrl = redirectUrl + "&refereeMemberId=" + memberId + "&refereeOpenid=" + openid;
		}
		
        log.debug("==>授权回调地址：{}", redirectUrl);

		try {
			String oauthUrl = this.wxMpService.oauth2buildAuthorizationUrl(
					redirectUrl, 
					WxConsts.OAuth2Scope.SNSAPI_USERINFO,
					null);

			log.debug("==>微信授权URL：{}", oauthUrl);

			this.response.sendRedirect(oauthUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	/**
	 * 网页授权回调处理方法
	 */
	@GetMapping("callback")
	public void callback(Long tenantId, Long activityId, Long refereeMemberId, String refereeOpenid, String pageComponent) {
		logger.debug("==>2、微信网页授权，回调处理");
		try {
			// 授权完后，默认跳转的页面
			String redirectUrl = this.properties.getWechat().getH5Url();

			// 1、接收微信传回的code参数
			String code = request.getParameter("code");
			
			// 2、通过Code换取access_token的票据
			WxMpOAuth2AccessToken oAuth2AccessToken = this.wxMpService.oauth2getAccessToken(code);
			// 3、通过access_token获取用户信息
			WxMpUser wxMpUser = this.wxMpService.oauth2getUserInfo(oAuth2AccessToken, null);
			
			// 根据商家ID，活动ID，openid查询会员是否存在
//			JkMember member = this.jkMemberService.getMember(tenantId, activityId, wxMpUser.getOpenId()) ;
//
//			if (null == member) { // 用户不存在
//				member = new JkMember() ;
//				member.setTenantId(tenantId);
//				member.setActivityId(activityId);
//				member.setOpenid(wxMpUser.getOpenId());
//				member.setNickname(wxMpUser.getNickname());
//				member.setHeadimgurl(wxMpUser.getHeadImgUrl());
//				
//				if(null != refereeMemberId && StringUtils.isNotBlank(refereeOpenid)) { // 设置推荐人
//					log.debug("==>关联推荐人：{}, {}", member.getNickname(), member.getRefereeOpenid());
//					member.setRefereeMemberId(refereeMemberId);
//					member.setRefereeOpenid(refereeOpenid);
//				}
//				
//				this.jkMemberService.save(member);
//			}
//			
//			JkActivity activity = this.jkActivityService.getById(activityId);
//
//			
//			redirectUrl = redirectUrl 
//					+ "?openid=" + wxMpUser.getOpenId() 
//					+ "&memberId=" + member.getId()
//					+ "&tenantId=" + tenantId
//					+ "&activityId=" + activityId
//					+ "&component=" + (null != activity.getTemplate() && StringUtils.isNotBlank(activity.getTemplate()) ? activity.getTemplate() : "default");
//			
//			// pageComponent指定使用组件显示（优先使用pageComponent，如果pageComponent没有，则使用component参数的组件）
//			if(null != pageComponent && StringUtils.isNotBlank(pageComponent) && !"null".equals(pageComponent)) {
//				redirectUrl = redirectUrl + "&pageComponent=" + pageComponent ;
//			}
			
			this.response.sendRedirect(redirectUrl);

			log.debug("==>用户信息：{}", wxMpUser);
			log.debug("==>跳转地址：{}", redirectUrl);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	@GetMapping(value = "/getUserInfo")
	public Object getUserInfo(Long tenantId, Long activityId, String openid) {
		log.debug("==3、根据openid获取用户信息");
//		JkMember member = this.jkMemberService.getMember(tenantId, activityId, openid) ;
//		if (null != member) {
//			return ResultBean.ok(member);
//		} else {
//			return ResultBean.failure();
//		}
		return null;
	}

	/**
	 * 根据openid获取用户信息
	 * 
	 * @param openid
	 */
//	@GetMapping(value = "/getUserInfo/{openid}")
//	public Object getUserInfo(@PathVariable String openid) {
//		log.debug("==3、根据openid获取用户信息");
//		WeixinOauthUser oauthUser = this.weixinOauthUserService.findByOpenId(openid);
//		if (null != oauthUser) {
//			return ResultBean.ok(oauthUser);
//		} else {
//			return ResultBean.failure();
//		}
//	}

}
